<?php
namespace app\modules\content\controllers;

use Yii;
use ac\controllers\AuthController;
use app\models\ContentCategory;
use app\models\ContentCategorySearch;
use app\models\Tags;
use app\models\TagsRelationships;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use ac\behaviors\Sort;


class ContentCategoryController extends AuthController
{

    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

	/*栏目列表*/
    public function actionCategoryList()
    {
        // P($this->get);
        $search = (new ContentCategorySearch())->search($this->get);
        if($search === false){//验证搜索参数不通过
            $count = 0;
            $contentCategoryList = array();
        }else{
            if(isset($this->get['type']) and $this->get['type'] == 'ele'){
                $flag = 'ele';
            }else{
                $flag = '';
            }
            if(isset( $this->get['parentid'] )){
                $parentid = $this->get['parentid'];
            }else{
                $parentid = 0;
            }
            // P($search);
            $contentCategoryList = ContentCategory::getTreeList($search, $flag, $parentid);
        }
        return Tool::showRes([0, '获取成功'], $contentCategoryList);
    }

    /*添加栏目*/
    public function actionAddCategory()
    {
        if(Yii::$app->request->isPost){
            $contentCategory = new ContentCategory;

            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*添加栏目*/
                if( ($catid = $contentCategory->addCategory($this->post)) == false){
                    $pass = false;
                    if($contentCategory->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $contentCategory->getErrors();//异常信息
                        if(array_key_exists("alias_repeat", $exception)){
                            $backInfo = ErrMap::getError(20007);
                            // list($errno, $errmsg) = ErrMap::getError(20007, '别名重复了');//返回信息
                        };
                    }else{
                        throw new \Exception('添加栏目异常失败');
                    }
                }

                /*增加标签 和 关联标签*/
                if($pass){
                    if(($res = $this->addTags($catid)) !== true){
                        $pass = false;
                        if(gettype($res) == 'array'){
                            $exception = $res;
                        }else{
                            throw new \Exception($res);
                        }
                    }
                }


                if($pass){
                    $backInfo = [0, '添加栏目成功'];//返回信息
                    $transaction->commit();
                }


            }catch(\Exception $exception){
                $transaction->rollback();       
            };


        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改栏目
    */
    public function actionModifyCategory()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $catid = isset($this->get['catid'])?$this->get['catid']:'';
            if($catid){
                $contentCategory = ContentCategory::find()
                        ->where('catid = :catid', [':catid' => $catid])->asArray()->one();
                if(!is_null($contentCategory)){
                    if(!empty($contentCategory['icon'])){
                        $contentCategory['icon'] = explode(',', $contentCategory['icon']);
                    }
                    if(!empty($contentCategory['preview'])){
                        $contentCategory['preview'] = explode(',', $contentCategory['preview']);
                    }
                    /*获取标签*/
                    $tagsRelationships = TagsRelationships::find()
                                ->select('unionid, {{%tags_relationships}}.tid')
                                ->joinWith('tag')
                                ->where('unionid = :unionid', [':unionid' => $catid])
                                // ->createCommand()->getRawSql();
                                ->asArray()->all();
                    // P($tagsRelationships);
                    $data = array(
                        'category' => $contentCategory,
                        'tags' => $tagsRelationships
                    );

                    return Tool::showRes([0, '获取成功'], $data);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $catid = isset($this->post['ContentCategory']['catid'])?intval($this->post['ContentCategory']['catid']):'';
            if(!$catid){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*修改栏目信息*/
                    $contentCategory = new ContentCategory;
                    if(!$contentCategory->modifyCategory($this->post, $catid)){
                        if($contentCategory->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $contentCategory->getErrors();//异常信息
                            if(array_key_exists("alias_repeat", $exception)){
                                $backInfo = ErrMap::getError(20007);
                                // list($errno, $errmsg) = ErrMap::getError(20007, '别名重复了');//返回信息
                            };
                        }else{
                            throw new \Exception('修改栏目失败');
                        }
                        $pass = false;
                    }

                    /*修改 tag 分4步*/
                    //1、获取老的标签
                    $tagsRelationships = TagsRelationships::find()
                                ->select('unionid, tid')
                                ->where('unionid = :unionid', [':unionid' => $catid])
                                ->asArray()->all();
                    //2、遍历老的标签，然后把热度-1
                    if(!is_null($tagsRelationships)){
                        foreach($tagsRelationships as $k => $v){
                            Tags::updateAllCounters(['heat' => -1], 'tid = :tid', [':tid' => $v['tid']]);
                        }
                    }

                    //3、删除所有老的标签
                    if(!is_null($tagsRelationships)){
                        foreach($tagsRelationships as $k => $v){
                            TagsRelationships::deleteAll('unionid = :unionid', [':unionid' => $catid]);
                        }
                    }

                    //4、按照新增的标签操作
                    /*增加标签 和 关联标签*/
                    $this->addTags($catid);


                    if($pass){
                        $backInfo = [0, '修改栏目成功'];//返回信息
                        $transaction->commit();
                    }


                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*是否显示1-不显示-2显示（是否显示操作）*/
    public function actionSetDisplay()
    {
        if(Yii::$app->request->isPost){
            $catid = isset($this->post['catid'])?$this->post['catid']:'';
            $contentCategory = ContentCategory::find()->select('display')
                                ->where('catid = :catid', [':catid' => $catid])->one();
            // P($contentCategory);
            if(!is_null($contentCategory)){
                $contentCategory->updateAll(['display' => Tool::changeBool($this->post['display']),], 'catid = :catid', [':catid' => $catid]);
                $backInfo = [0, '设置栏目显示状态成功'];//返回信息
            };
        }

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    排序
    tree型数据，是按照sort正序排列
    */
    public function actionSetSort()
    {
       if(Yii::$app->request->isPost){
            // P($this->post);
            //取出被排序的数据
            $sortId = isset($this->post['sort'])?$this->post['sort']:'';
            //目标对象  ‘before’在之上面，否则在下面
            $targetId = isset($this->post['target'])?$this->post['target']:'';
            if($sortId and $targetId){
                if($this->setSortTreeList(new ContentCategory, $sortId, $targetId, $this->post['location'])){
                    $backInfo = [0, '设置栏目排序成功'];//返回信息
                }
            }
            // P($backInfo);

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };


       }
       return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除栏目,包括子栏目（真删除）*/
    public function actionDeleteCategory()
    {
        $catid = isset($this->get['catid'])?$this->get['catid']:'';
        if($catid){
            $contentCategory = new ContentCategory;
            if(($res = $contentCategory->deleteCategory($catid)) === true){
                $backInfo = [0, '删除栏目成功'];//返回信息
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), '') ) != 'boolean'){
                    return $res;
                };
            }else{
                return Tool::showRes(ErrMap::getError($res));
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }

    /*检查父ID是否存在*/
    private function checkHasParId($catid)
    {
        if($catid == 0){
            return true;
        }
        $contentCategory = ContentCategory::find()->where('catid = :catid', [':catid' => $catid])->one();
        // P($contentCategory);
        if(is_null($contentCategory)){
            return false;
        }else{
            return true;
        };
    }


    /*增加标签 和 关联标签 仅限本控制器使用*/
    private function addTags($unionid, $flag = 1)
    {
        $pass = true;
        /*增加tag标签*/
        $updataTags = [];//需要增加热度的标签ID
        if(isset($this->post['Tags']) and gettype($this->post['Tags']) == 'array'){
            foreach($this->post['Tags'] as $k => $v){
                if(empty($v['tid'])){
                    $tags = new Tags;
                    $data = array(
                        'Tags' => $v
                    );
                    $data['Tags']['heat'] = 1;
                    if( ($tid = $tags->addTag($data, true)) > 0 ){
                        array_push($updataTags, $tid);
                    }else{
                        $pass = false;
                        if($tags->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $tags->getErrors();//异常信息
                        }else{
                            $exception = '添加标签异常失败';
                        }
                        break;
                    }
                }else{
                    array_push($updataTags, $v['tid']);
                    Tags::updateAllCounters(['heat' => 1], 'tid = :tid', [':tid' => $v['tid']]);
                }
            };
        }

        /*添加标签关联*/
        // P($updataTags);
        if($pass){
            foreach($updataTags as $k => $v){
                $tagsRelationships = new TagsRelationships;
                $data = array(
                    'TagsRelationships' => array(
                        'unionid' => $unionid,
                        'tid' => $v,
                        'flag' => $flag
                    )
                );
                if(!$tagsRelationships->addRelationships($data)){
                    $pass = false;
                    if($tagsRelationships->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $tagsRelationships->getErrors();//异常信息
                    }else{
                        $exception = '添加标签关联失败';
                    }
                    break;
                }
            }
        }

        if($pass){
            return true;
        }else{
            return $exception;
        }

    }


    /*取出 自定义字段 关联*/
    public function actionAttrList()
    {
        $catid = isset($this->get['catid'])?$this->get['catid']:0;
        if($catid){
            $categoryAttrRelationships = new CategoryAttrRelationships;
            $categoryAttrRelationshipsList = $categoryAttrRelationships::find()
                            ->joinWith('attrName')
                            ->where('unionid = :unionid', [':unionid' => $catid])
                            ->orderBy(['sort' => SORT_DESC])
                            // ->createCommand()->getRawSql();
                            ->asArray()->all();
            // P($categoryAttrRelationshipsList);
        }else{
            $categoryAttrRelationshipsList = array();
        }
        return Tool::showRes([0, '获取成功'], $categoryAttrRelationshipsList);
    }

    /*设置 自定义字段 关联*/
    public function actionSetAttr()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);
            $unionid = isset($this->post['unionid'])?intval($this->post['unionid']):'';
            if(!$unionid){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*删除所有的老数据*/ //没有传数据，说明是清除
                    CategoryAttrRelationships::deleteAll('unionid = :unionid', [':unionid' => $unionid]);

                    if( isset($this->post['data']) and is_array($this->post['data']) ){
                        /*遍历添加新数据*/
                        foreach(array_reverse($this->post['data']) as $k => $v){
                            $data = array(
                                'CategoryAttrRelationships' => array(
                                    'unionid' => $unionid,
                                    'attr_id' => $v['attr_id'],
                                )
                            );

                            $categoryAttrRelationships = new CategoryAttrRelationships;
                            if(!$categoryAttrRelationships->addRelationships($data)){
                                if($categoryAttrRelationships->hasErrors()){
                                    $backInfo = ErrMap::getError(10005);//返回信息
                                    $exception = $categoryAttrRelationships->getErrors();//异常信息
                                }else{
                                    throw new \Exception('设置自定义字段失败');
                                }
                            }

                        };
                    }


                    if($pass){
                        $backInfo = [0, '设置自定义字段成功'];//返回信息
                        $transaction->commit();
                    }


                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }



}